package com.elink.enginerring.service.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elink.enginerring.co.BaseCo;
import com.elink.enginerring.co.ThesisCo;
import com.elink.enginerring.common.CoinEnum;
import com.elink.enginerring.common.Constant;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.common.HessianResultEnum;
import com.elink.enginerring.common.HessionEnum;
import com.elink.enginerring.common.HessionInfluenceEnum;
import com.elink.enginerring.common.Pagination;
import com.elink.enginerring.dao.BrowseRecordMapper;
import com.elink.enginerring.dao.DetailCategoryMapper;
import com.elink.enginerring.dao.KeyWordMapper;
import com.elink.enginerring.dao.OrdersMapper;
import com.elink.enginerring.dao.SecondaryCategoryMapper;
import com.elink.enginerring.dao.ThesisMapper;
import com.elink.enginerring.domain.BrowseRecord;
import com.elink.enginerring.domain.DetailCategory;
import com.elink.enginerring.domain.KeyWord;
import com.elink.enginerring.domain.Orders;
import com.elink.enginerring.domain.SecondaryCategory;
import com.elink.enginerring.domain.Thesis;
import com.elink.enginerring.hessian.CoinHessianService;
import com.elink.enginerring.hessian.PersonDynamicHessianService;
import com.elink.enginerring.service.ThesisService;
import com.elink.enginerring.util.JSONUtil;
import com.elink.enginerring.util.UUIDUtil;
import com.elink.enginerring.vo.HessianMessage;
import com.elink.enginerring.vo.ThesisVo;

@Service
public class ThesisServiceImpl implements ThesisService {
	@Autowired
	private ThesisMapper thesisMapper;
	@Autowired
	private KeyWordMapper keyWordMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private BrowseRecordMapper browseRecordMapper;
	@Autowired
	private DetailCategoryMapper detailCategoryMapper;
	@Autowired
	private SecondaryCategoryMapper secondaryCategoryMapper;
	@Autowired
	private PersonDynamicHessianService personDynamicHessianService;
	@Autowired
	private CoinHessianService coinHessianService;
	@Override
	public Map<String, Object> getFilesList(ThesisCo co) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", thesisMapper.selectList(co));
		map.put("Pagination", new Pagination(co, thesisMapper.selectCount(co)));
		
		// 将关键词存入表中
		KeyWord kw = keyWordMapper.selectByKeyWord(co.getKeyWord());
		if (kw != null) {// 表示该关键词存在
			kw.setSearchCount(kw.getSearchCount() + 1);
			keyWordMapper.updateByPrimaryKeySelective(kw);
		} else {
			if (co.getKeyWord() != null && co.getKeyWord() != "") {
				KeyWord newKw = new KeyWord();
				newKw.setName(co.getKeyWord());
				newKw.setSearchCount(1);
				newKw.setSearchTime(new Date());
				keyWordMapper.insertSelective(newKw);
			}
		}
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> add(Thesis thesis) {
		String thesisId = UUIDUtil.getUUID();
		thesis.setUploadTime(new Date());
		thesis.setThesisId(thesisId);
		thesisMapper.insertSelective(thesis);
		//论文备份
		//远程备份
		try {
			personDynamicHessianService.addPersonDynamic(HessionEnum.UPLOADLIBRARY.getIndex(),thesis.getTypeId(),
					thesis.getName(),thesis.getIntroduction(),thesis.getUserId(),thesisId,null);
		} catch (Exception e) {
			  Logger logger = Logger.getLogger(ThesisServiceImpl.class);
			  logger.info("远程添加论文图书馆资料失败"+e);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		//审核成功后奖励的E币数
//		try {
//			map = coinHessianService.getCoinRule(CoinEnum.UPLOADLIBRARY.getIndex());
//		} catch (Exception e) {
//			  Logger logger = Logger.getLogger(ThesisServiceImpl.class);
//			  logger.info("远程获取上传论文图书馆资料奖励的E币数失败"+e);
//		}
		
		//添加影响值
		try{
			coinHessianService.modifyInfluenceValue(thesisId, HessionInfluenceEnum.UPLOADTHESIS.getIndex(), thesis.getUserId());
		}catch (Exception e){
			  Logger logger = Logger.getLogger(ThesisServiceImpl.class);
			  logger.info("远程添加上传论文资料获取影响值失败"+e);
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> update(Thesis thesis,String userId) {
		//校验是否有修改的资格
		Thesis old = thesisMapper.selectByUserId(userId,thesis.getThesisId());
		if(old !=null){
			thesisMapper.updateByPrimaryKeySelective(thesis);
			//远程更新
			try {
				personDynamicHessianService.modifyPersonDynamic(HessionEnum.MODIFYLIBRARY.getIndex(),thesis.getTypeId(),
						thesis.getName(),thesis.getIntroduction(),thesis.getThesisId(),thesis.getUserId());
			} catch (Exception e) {
				Logger logger = Logger.getLogger(ThesisServiceImpl.class);
				logger.info("远程更新论文图书馆资料失败"+e);
			}
			
			//论文备份
			return JSONUtil.getJSON(ErrorType.SUCCESS);
			
		}else{
			return JSONUtil.getJSON(ErrorType.UPDATE_ERROR);
		}
	}

	@Override
	public Map<String, Object> getInfo(String thesisId, String userId) {		
		ThesisVo thesisVo  =  thesisMapper.selectInfo(thesisId,userId);
		
		// 更新论文的浏览次数
		thesisVo.setBrowseCount(thesisVo.getBrowseCount()+1);
		thesisMapper.updateByPrimaryKeySelective(thesisVo);
		
		// 往浏览记录表面插入数据
		if (userId != null) {
			BrowseRecord b = new BrowseRecord();
			b.setBrowseTime(new Date());
			b.setThesisId(thesisId);
			b.setUserId(userId);
			browseRecordMapper.insertSelective(b);
		}
		
		// 根据上传时间查询出上一篇和下一篇
		Thesis fpre = thesisMapper.selectPre(thesisVo.getUploadTime());
		Thesis fnext = thesisMapper.selectNext(thesisVo.getUploadTime());
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("file", thesisVo);
		map.put("fpre", fpre);
		map.put("fnext", fnext);
		// 查询该论文的分类
		SecondaryCategory sec = secondaryCategoryMapper.selectByPrimaryKey(thesisVo.getScId());
		DetailCategory  detail = detailCategoryMapper.selectByPrimaryKey(thesisVo.getDcId());
		Map<String, Object> category = new HashMap<String, Object>();
		category.put("secCategory", sec);
		category.put("detailCategory", detail);
		
		map.put("category", category);
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}
	
	
	@Override
	public Map<String, Object> getShare(String thesisId, String userId) {		
		ThesisVo thesisVo  =  thesisMapper.selectInfo(thesisId,userId);
		Map<String, Object> map = new HashMap<String, Object>();
		// 统计该作者上传共享的资料的资料
		map.put("share", thesisMapper.getShare(thesisVo.getUserId()));
		map.put("shareCount",thesisMapper.countUploadByUserId(thesisVo.getUserId(),null));

		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> getDownLoadRank(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,thesisMapper.getDownLoadRank(count));
	}

	@Override
	public Map<String, Object> getRelevant(String thesisId, int count) {
		Thesis thesis = thesisMapper.selectByPrimaryKey(thesisId);
		if (thesis != null) {
			// 根据一级分类和二级分类去找相关的工程资料
			return JSONUtil.getJSON(ErrorType.SUCCESS,thesisMapper.selectRelevantList(thesis.getTcId(),thesis.getScId(), count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getLike(String thesisId, int count) {
		Thesis thesis = thesisMapper.selectByPrimaryKey(thesisId);
		if (thesis != null) {
			return JSONUtil.getJSON(ErrorType.SUCCESS,thesisMapper.getLike(thesis.getScId(),count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getKeyWord(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,keyWordMapper.getKeyWord(count));
	}

	@Override
	public Map<String, Object> getRelevantType(String thesisId, int count) {
		Thesis thesis = thesisMapper.selectByPrimaryKey(thesisId);
		if (thesis != null) {
			return JSONUtil.getJSON(ErrorType.SUCCESS,	detailCategoryMapper.selectInfoClassify(thesis.getTcId(), thesis.getScId(),thesis.getDcId(), count));
		} else {
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> download(HttpServletResponse response,HttpServletRequest request, String userId, String thesisId) throws IOException{
		 Thesis thesis = thesisMapper.selectByPrimaryKey(thesisId);
			if(thesis != null){
				HessianMessage msg  = coinHessianService.modifyCoin(thesisId, CoinEnum.DOWNLOADLIBRARY.getIndex(), 
						(Float.valueOf(thesis.getPrice())).intValue(), userId, thesis.getUserId());
				if(msg.getCode() == HessianResultEnum.Success.getIndex()){//请求成功
					// 生成订单
					Orders order = new Orders();
					order.setThesisId(thesisId);
					order.setTime(new Date());
					order.setUserId(userId);
					order.setOrderId( UUIDUtil.getUUID());
					ordersMapper.insertSelective(order);


					BufferedInputStream bis = null;
					HttpURLConnection httpUrl = null;
					URL url = null;
					// 建立链接
					url = new URL(Constant.DOWNLOAD_URL+thesis.getPath());
					httpUrl = (HttpURLConnection) url.openConnection();
					// 连接指定的资源
					httpUrl.connect();
					// 获取网络输入流
					bis = new BufferedInputStream(httpUrl.getInputStream());
					
					response.setContentType("multipart/form-data"); //设置文件ContentType类型，这样设置，会自动判断下载文件类型
					java.io.File fileLoad = new java.io.File(Constant.DOWNLOAD_URL+thesis.getPath());
					response.setHeader("Content-Disposition", "attachment;filename="+ fileLoad.getName());
					ServletOutputStream  o = response.getOutputStream();
					byte b[] = new byte[1024];
				
					int n = 0;
					while ((n = bis.read(b)) != -1) {
						o.write(b, 0, n);
					}
					o.close();  
					o.flush(); 
					bis.close();
					httpUrl.disconnect();
					//远程备份
					try {
						personDynamicHessianService.addPersonDynamic(HessionEnum.DOWNLOADLIBRARY.getIndex(),
								thesis.getTypeId(),thesis.getName(),thesis.getIntroduction(),userId,thesis.getThesisId(),thesis.getUserId());
					} catch (Exception e) {
						Logger logger = Logger.getLogger(ThesisServiceImpl.class);
						logger.info("远程下载论文图书馆资料失败"+e);
					}
					
					//更新资料的下载次数
					thesis.setDownloadCount(thesis.getDownloadCount()+1);
					thesisMapper.updateByPrimaryKeySelective(thesis);
					
					return JSONUtil.getJSON(ErrorType.SUCCESS);
				}else{
					return JSONUtil.getJSON(ErrorType.REWARD_ERROR,msg.getMsg());
				}
			}else{
				return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
			 }		  
	}

	@Override
	public Map<String, Object> getUploadByUserId(BaseCo co, String userId,String keyWord) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", thesisMapper.getUploadByUserId(co, userId,keyWord));
		map.put("Pagination",new Pagination(co, thesisMapper.countUploadByUserId(userId,keyWord)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getDownLoadByUserId(BaseCo co, String userId,String keyWord) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", thesisMapper.getDownLoadByUserId(co, userId,keyWord));
		map.put("Pagination",new Pagination(co, thesisMapper.countDownLoadByUserId(userId,keyWord)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getThesisList(int scId) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, thesisMapper.selectThesisList(scId));
	}

	@Override
	public Map<String, Object> getThesisBest(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, thesisMapper.selectThesisBest(count));
	}
}
